package org.dfrt.own.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang
 * ClassName: LoginFilter
 * Description: 登陆过滤器
 * date: 2023/10/5 13:35
 * @since JDK 8
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.强制转换
        HttpServletRequest request = (HttpServletRequest) req;
        //2.获取请求资源路径
        String requestURI = request.getRequestURI();
        //3.判断是否包含登录相关资源路径,同时排除css,js，图片等
//        if (requestURI.contains("/login.jsp") || requestURI.contains("/loginServlet")||requestURI.contains("/checkCodeServlet")||requestURI.contains("/css/")||requestURI.contains("/js/")||requestURI.contains("/fonts/")) {
        if (requestURI.contains("/login.jsp") ||requestURI.contains("/index.jsp") ||requestURI.contains("/user/login.action")||requestURI.contains("/user/register.action")) {

        //放行
            chain.doFilter(req, resp);
        } else {
            //4.判断是否登录
            Object user = request.getSession().getAttribute("user");
            if (user != null) {
                //已登录，放行
                chain.doFilter(req, resp);
            }else {
                //未登录，跳转登陆页面
                Map<String,String> msgmap = new HashMap<>();
                msgmap.put("sta","yes");
                msgmap.put("msg","请登录");
                request.setAttribute("msgmap",msgmap);
                request.getRequestDispatcher("/toLogin.jsp").forward(request,resp);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
